package com.example.project.webControlleer;

import com.example.project.dao.UserDAO;
import com.example.project.pojo.User;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

@Controller
@RequestMapping("web")
public class WebRegisterController {
private final UserDAO userDAO = new UserDAO();
    @RequestMapping("register")
    public String register() {

        return "web/register";
    }

    @RequestMapping("checkPhoneBeforeRegister")
    @ResponseBody
    public String checkPhoneBeforeRegister(String userphone){

        System.out.println(userphone+"0....");
        String msg="1";
        if (!userDAO.CheckUserPhoneBeforeRegister(userphone)){
          msg="2";
        }
        return msg;
    }
    @RequestMapping("check")
    public String check(User user, MultipartFile face, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");



        String filepath = request.getServletContext().getRealPath("/static/uploadimages");
        if (face.getSize() > 0) {
            String orginalfilename = face.getOriginalFilename();
            int index = orginalfilename.lastIndexOf(".");
            String fileext = orginalfilename.substring(index + 1);
            String filename = UUID.randomUUID() + "." + fileext;
            user.setUserFace(filename);
            try {
                face.transferTo(new File(filepath + "/" + filename));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            user.setUserFace("1.jpg");
        }
        userDAO.Register(user);
        return "redirect:/web/login";

    }
}
